import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Form, Input, Button, message } from "antd";
import useData from "@/store";
import api from "@/fetch";

import "./index.less";

const LoginForm: React.FC<{ handleSetIsLogin: (isLogin: boolean) => void }> = (
  props,
) => {
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(false);

  const onFinish = (values: { phone: string; password: string }) => {
    setIsLoading(true);
    api
      .post("/api/v1/auth/login", values)
      .then((res) => {
        useData
          .getState()
          .setUserInfo({ token: res.data.token, ...res.data.userInfo });
        navigate("/system", { replace: true });
      })
      .catch((error) => {
        message.error(error?.message || "登录失败");
      })
      .finally(() => {
        setIsLoading(false);
      });
  };

  return (
    <Form
      name="login_form"
      onFinish={onFinish}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 18 }}
    >
      <Form.Item
        label="手机号码"
        name="phone"
        rules={[
          { required: true, message: "请输入手机号码!" },
          {
            pattern: /^[1-9]\d{10}$/,
            message: "请输入正确的手机号码!",
          },
        ]}
      >
        <Input className="custom-input" />
      </Form.Item>

      <Form.Item
        label="密码"
        name="password"
        rules={[
          { required: true, message: "请输入密码!" },
          { min: 5, message: "密码不能少于5个字符!" },
          { max: 16, message: "密码不能大于16个字符!" },
        ]}
      >
        <Input.Password className="custom-input" />
      </Form.Item>

      <Form.Item wrapperCol={{ offset: 6, span: 18 }}>
        <div className="btn-center">
          <Button type="primary" htmlType="submit" loading={isLoading}>
            登录
          </Button>
        </div>
        <div
          onClick={() => props.handleSetIsLogin(false)}
          className="btn-center"
          style={{ marginTop: "20px", cursor: "pointer", color: "blue" }}
        >
          注册
        </div>
      </Form.Item>
    </Form>
  );
};

export default LoginForm;
